<template>
	<view class="container" :data-is="isFw" :data-gwtype="gwTypeValue">
		<view class="form-container">
			<!-- 发文流程，传真电报，等其他未知类型 -->
			<FawenLiucheng v-if="formData.isFw === 'true' || gwTypeValue === 'sdj_aqsc' || (!['fw', 'sw', 'cbj','qsj', 'qsbj', 'lbbg', 'wcbg'].includes(gwTypeValue) && gwTypeValue !== '')"
				:formData="formData"
				:signImages="signImages"
				:sealOptionsKey="sealOptionsKey"
				:loadFile="loadFile"
				:handleLongPress="handleLongPress">
			</FawenLiucheng>

			<!-- 外出报告单布局 -->
			<WaichuBaogaoDan v-else-if="gwTypeValue === 'wcbg'"
				:formData="formData"
				:signImages="signImages"
				:sealOptionsKey="sealOptionsKey"
				:handleLongPress="handleLongPress">
			</WaichuBaogaoDan>

			<!-- 来宾报告布局 -->
			<LaibinBaogao v-else-if="gwTypeValue === 'lbbg'"
				:formData.sync="formData"
				:signImages="signImages"
				:sealOptionsKey="sealOptionsKey"
				:handleLongPress="handleLongPress">
			</LaibinBaogao>

			<!-- 呈报件流程 -->
			<ChenbaojianLiucheng v-else-if="gwTypeValue === 'cbj'"
				:formData="formData"
				:signImages="signImages"
				:sealOptionsKey="sealOptionsKey"
				:loadFile="loadFile"
				:handleLongPress="handleLongPress"
				:gwTypeValue="gwTypeValue">
			</ChenbaojianLiucheng>

			<!-- 收文流程 -->
			<ShouwenLiucheng v-else-if="gwTypeValue === 'sw' || gwTypeValue === 'qsj'"
				:formData="formData"
				:signImages="signImages"
				:sealOptionsKey="sealOptionsKey"
				:loadFile="loadFile"
				:handleLongPress="handleLongPress"
				:gwTypeValue="gwTypeValue">
			</ShouwenLiucheng>
		</view>
		<br>
		<!-- 浮动操作按钮 -->
		<view class="float-action-btn" v-if="!readonly" @click="toggleMenu">
			<text class="icon">操作</text>
		</view>

		<!-- 展开菜单 -->
		<transition name="slide">
			<view v-if="isExpanded && !readonly" class="action-menu">
				<!-- 根据gwTypeValue动态调整按钮顺序和显示 -->
				<template v-if="gwTypeValue === 'wcbg'">
					<!-- 签收按钮（新增，蓝色） -->
					<view class="menu-item menu-item-sign-off" @click="handleMenuClick('签收')">
						签收
					</view>
				</template>
					<!-- 签名按钮（绿色）- 其他流程默认顺序 -->
					<view class="menu-item menu-item-sign" @click="openSealDialog">
						签章
					</view>
					<!-- 批注按钮（蓝色） -->
					<view class="menu-item menu-item-comment" @click="handleTextSign">
						批注
					</view>
				<!-- 退回按钮（红色） -->
				<view class="menu-item menu-item-reject" @click="handleMenuClick('退回')">
					退回
				</view>

				<!-- 发送按钮（橙色） -->
				<view class="menu-item menu-item-send" @click="handleMenuClick('发送')">
					发送
				</view>
			</view>
		</transition>

		<!-- 签名弹窗 -->
		<view v-if="showSealDialog" class="seal-dialog-bg">
			<view class="seal-dialog comment-dialog">
				<view class="dialog-content">
					<view class="form-item">
						<text class="form-label">请选择签章位置：</text>
						<picker :range="sealOptions" @change="onSealPositionChange" class="form-picker">
							<view class="picker-content">
								<text>{{ sealOptions[sealIndex] }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="form-label">是否添加日期：</text>
						<switch :checked="withDate" @change="onDateChange" color="#007AFF" />
					</view>
				</view>
				<view class="dialog-footer">
					<button type="default" class="btn-cancel" @click="showSealDialog=false">取消</button>
					<button type="primary" class="btn-confirm" @click="addSeal">确定</button>
				</view>
			</view>
		</view>

		<!-- 图章列表弹窗 -->
		<view v-if="showSealList" class="seal-list-dialog-bg">
			<view class="seal-list-dialog">
				<view class="seal-list-title">请选择图章：</view>
				<scroll-view scroll-y class="seal-list-content">
					<view v-for="(seal, index) in sealList" :key="index" class="seal-item"
						@click="selectSeal(seal)">
						<image
							:src="seal.imageUrl.startsWith('data:image') ? seal.imageUrl : `data:image/png;base64,${seal.imageUrl}`"
							mode="aspectFit" class="seal-image"></image>
						<text class="seal-name">{{seal.name}}</text>
					</view>
				</scroll-view>
				<view class="seal-list-footer">
					<button type="default" size="mini" @click="showSealList = false">取消</button>
				</view>
			</view>
		</view>

		<!-- 用于生成签名的隐藏canvas -->
		<canvas canvas-id="signatureCanvas"
			style="width: 300px; height: 100px; position: absolute; left: -9999px; top: -9999px;"></canvas>
		<!-- 批注弹窗 -->
		<view v-if="showCommentDialog" class="seal-dialog-bg">
			<view class="seal-dialog comment-dialog">
				<view class="dialog-content">
					<view class="form-item">
						<text class="form-label">请选择签章位置：</text>
						<picker :range="sealOptions" @change="onCommentPositionChange" class="form-picker">
							<view class="picker-content">
								<text>{{ sealOptions[commentPositionIndex] }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="form-label">批注内容</text>
						<input type="text" v-model="commentContent" placeholder="请输入批注内容" class="form-input" />
					</view>
					<view class="form-item">
						<text class="form-label">字体颜色</text>
						<picker :range="['黑色', '红色', '黄色', '白色', '绿色', '蓝色', '紫色']" @change="onColorChange"
							class="form-picker">
							<view class="picker-content">
								<text :style="{ color: textSignColor }">{{ colorNames[textSignColor] }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="form-label">字体大小</text>
						<input type="number" v-model="textSignFontSize" min="12" max="72" class="form-input" />
					</view>
				</view>
				<view class="dialog-footer">
					<button type="default" class="btn-cancel" @click="showCommentDialog=false">取消</button>
					<button type="primary" class="btn-confirm" @click="addComment">确定</button>
				</view>
			</view>
		</view>

		<!-- 退回弹窗 -->
		<view v-if="showBackDialog" class="seal-dialog-bg">
			<view class="seal-dialog comment-dialog">
				<view class="form-item">
				<text class="form-label">请填写退回信息：</text>
				</view>
				<view class="dialog-content">
					<view class="form-item">
						<text class="form-label">退回节点：</text>
						<picker :range="backNodes" range-key="activityName" @change="onBackNodeChange" class="form-picker">
							<view class="picker-content">
								<text>{{ backNodes[backNodeIndex] ? backNodes[backNodeIndex].activityName : '请选择退回节点' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="form-label">退回意见：</text>
						<textarea v-model="backCommentContent" placeholder="请输入退回意见" class="form-input" />
					</view>
				</view>
				<view class="dialog-footer">
					<button type="default" class="btn-cancel" @click="showBackDialog=false">取消</button>
					<button type="primary" class="btn-confirm" @click="confirmBack">确定</button>
				</view>
			</view>
		</view>

		<!-- 发送弹窗 -->
		<view v-if="showSendDialog" class="seal-dialog-bg">
			<view class="seal-dialog comment-dialog" style="height: 650rpx;">
				<view class="form-item">
				<text class="form-label">选择下一环节和参与者：</text>
				</view>
				<view class="dialog-content">
					<view class="form-item">
						<text class="form-label">下一环节：</text>
						<picker @change="onNextTaskChange" :range="nextTasks" range-key="label" :value="nextTaskIndex" class="form-picker">
							<view class="picker-content"><text>{{nextTasks[nextTaskIndex] ? nextTasks[nextTaskIndex].label : '请选择'}}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>

					<view class="form-item" v-if="showParticipants">
						<text class="form-label">参与人员：</text>
						<view class="search-container" @click.stop>
							<input 
								type="text" 
								v-model="searchKeyword" 
								class="search-input"
								placeholder="请输入姓名或部门搜索"
								@input="handleSearch"
								@click="showAllParticipants"
								style="z-index: 99999;"
							/>
							<scroll-view 
								scroll-y 
								class="search-results" 
								v-if="showSearchResults && filteredParticipants.length > 0"
								style="z-index: 99999;"
							>
								<view 
									v-for="(item, index) in filteredParticipants" 
									:key="index"
									class="search-item"
									@click="selectParticipant(item)"
								>
									<text>{{item.userName}} ({{item.employee.office.officeName}})</text>
								</view>
							</scroll-view>
						</view>
					</view>

				</view>
				<br/><br/>
				<view class="dialog-footer">
					<button type="default" class="btn-cancel" @click="showSendDialog=false">取消</button>
					<button type="primary" class="btn-confirm" @click="confirmSend">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		checkLogin
	} from '@/common/auth.js';
	import signature from '@/common/signature.js';
	import FawenLiucheng from '@/components/FawenLiucheng.vue'
	import WaichuBaogaoDan from '@/components/WaichuBaogaoDan.vue'
	import LaibinBaogao from '@/components/LaibinBaogao.vue'
	import ChenbaojianLiucheng from '@/components/ChenbaojianLiucheng.vue'
	import ShouwenLiucheng from '@/components/ShouwenLiucheng.vue'
	import config from '@/common/config.js';
	export default {
		components: {
			FawenLiucheng,
			WaichuBaogaoDan,
			LaibinBaogao,
			ChenbaojianLiucheng,
			ShouwenLiucheng
		},
		data() {
			return {
				formData: {
					tiaozhuan: '',
					title: '',
					zhuban: '',
					nigaoren: '',
					dianhua: '',
					zhusong: '',
					chaosong: '',
					fujian: '',
					fenfa: '',
					wenjianzi: '',
					nianhao: '',
					bianhao: '',
					fawenhao: '',
					zwfs: '',
					fjfs: '',
					dazi: '',
					jiaodui: '',
					yinshua: '',
					yongyin: '',
					fengfa: '',
					bgssh: '', // 办公室意见
					qianfa: '', // 领导批示意见
					fabufanwei: '', // 来文字号 (收文用)
					remarks: '', // 办理结果
					// New fields for '呈报件'
					jubenNianhao: '', // 局办登记 年号
					jubenBianhao: '', // 局办登记 编号
					bumenNianhao: '', // 部门(单位)登记 年号
					bumenBianhao: '', // 部门(单位)登记 编号
					zhucheng: '', // 主呈
					shenYueOpinion: '', // 审阅意见 (text)
					departmentAuditOpinion: '', // 部门(单位)审核意见 (text)
					chengbaoUnit: '', // 呈报(部门)单位

					// New fields for '外出报告单'
					position: '', // 职务
					reason: '', // 事由
					destination: '', // 目的地
					travelTime: '', // 时间
					leaderInCharge: '', // 主持工作负责同志
					chargeLeaderApproval: '', // 分管领导审批
					mainLeaderApproval: '', // 主要负责人审批

					// New fields for '来宾报告'
					reportDepartment: '', // 报告部门
					reportTime: '', // 报告时间
					guestUnit: '', // 来宾单位
					numberOfGuests: '', // 来宾人数
					mainGuestName: '', // 主宾姓名
					mainGuestPosition: '', // 主宾职务
					accompanyingPersonnel: '', // 主要陪同人员
					itinerary: '', // 行程安排

					isFw: 'false', // 默认为收文，但根据数据实际情况动态改变
					
					createtime: '', // 来文时间 (收文用)
					list: [],
					bpm: { // Ensure bpm is initialized
						taskId: '',
						procInsId: '',
						activityId: '',
						priority: ''
					}
				},
				gwTypeValue: '', // 公文类型，例如 'sw', 'fw', 'czdb', 'cbj'
				isExpanded: false,
				menuItems: ['签名', '批注', '退回', '发送'],
				showSealDialog: false,
				sealOptions: [], // 动态设置
				sealOptionsKey: [], // 动态设置
				sealIndex: 0,
				withDate: true,
				sealList: [],
				showSealList: false,
				isSignServerLoggedIn: false,
				// 批注相关数据
				showCommentDialog: false,
				commentPositionIndex: 0,
				commentContent: '',
				textSignColor: '#000000',
				textSignFontSize: '60',
				textSignFontFamily: '宋体',
				colorNames: {
					'#000000': '黑色',
					'#FF0000': '红色',
					'#FFFF00': '黄色',
					'#FFFFFF': '白色',
					'#00FF00': '绿色',
					'#0000FF': '蓝色',
					'#800080': '紫色'
				},
				signImages: {}, // 存储签章和批注图片，每个位置对应一个数组
				backNodes: [], // 存储退回列表数据
				showBackDialog: false, // 控制退回弹窗显示
				backNodeIndex: 0, // 选中的退回节点索引
				backCommentContent: '', // 退回意见内容
				showPreviewDialog: false, // 控制预览弹窗显示
				previewImage: '', // 预览图片URL
				// 发送相关数据
				showSendDialog: false,
				nextTasks: [],
				nextTaskIndex: 0,
				participants: [],
				selectedParticipants: '', // 更改为单个userCode字符串，而非数组
				showParticipants: false,
				selectedParticipantIndex: 0, // 新增：选中的参与人员索引
				// 搜索相关数据
				searchKeyword: '',
				showSearchResults: false,
				filteredParticipants: [],
				isFw:''
			};
		},
		async onLoad(options) {
			if (!checkLogin()) {
				return;
			}
			await this.loginSignServer();
			// 处理isFw和gwTypeValue参数，优先使用页面传递的参数
			if (options) {
				if (typeof options.isFw !== 'undefined') {
					
					this.formData.isFw = options.isFw;
					this.isFw = options.isFw;
					// 根据isFw设置导航栏背景色
					uni.setNavigationBarColor({
						frontColor: '#ffffff',
						backgroundColor: options.isFw === 'true' ? '#ec635d' : '#0089D9'
					});
				}
				this.gwTypeValue = options.gwType;
				
			}
			if (options && typeof options.readonly !== 'undefined') {
				this.readonly = options.readonly == 1 || options.readonly === '1';
			}
			await this.loadFormData();
		},
		methods: {
			async loadFormData() {
				try {
					const response = await this.$u.api.getDaibanForm({
						__sid: uni.getStorageSync('sessionid'),
						id: uni.getStorageSync('taskId'),
						bizKey: uni.getStorageSync('bizKey'),
						status: 1
					});
					if (response && response.data) {
						this.formData = response.data;
						// 动态设置签章选项 based on isFw and gwTypeValue
						if (this.isFw == 'true') {
							this.sealOptions = ['签发', '审核', '会签', '核稿', '办公室审核'];
							this.sealOptionsKey = ['qfGrid', 'syGrid', 'hqGrid', 'hgGrid', 'sGrid1'];
						} else if (this.gwTypeValue === 'cbj') {
							this.sealOptions = ['审阅', '办公室意见', '领导批示', '会签', '部门(单位)审核','办理结果'];
							this.sealOptionsKey = ['syGrid', 'sGrid1', 'qfGrid', 'hqGrid', 'hgGrid', 'jgGrid'];
						} else if (this.gwTypeValue === 'wcbg') {
							this.sealOptions = ['办公室意见', '分管领导审批', '主要负责人审批'];
							this.sealOptionsKey = ['sGrid1', 'syGrid', 'qfGrid'];
							this.formData.remarks = ''; // 外出报告单没有办理结果
							// delete this.rules.remarks; // 移除办理结果的校验规则
						} else if (this.gwTypeValue === 'lbbg') {
							this.sealOptions = ['办公室意见', '领导批示'];
							this.sealOptionsKey = ['sGrid1', 'qfGrid'];
							this.formData.remarks = ''; // 来宾报告没有办理结果
							// delete this.rules.remarks; // 移除办理结果的校验规则
						} else { // For '收文' (default non-发文)
							this.sealOptions = ['办公室意见', '领导批示', '办理结果'];
							this.sealOptionsKey = ['sGrid1', 'qfGrid', 'hqGrid'];
						}

						// 获取签名列表
						const userName = uni.getStorageSync('userName');
						if (userName) {
							// 先清空所有签名位置
							const signResult = await signature.listSignatures(userName, uni.getStorageSync('bizKey'));
							if (signResult && signResult.status.errCode === "0" && signResult.data) {
								// 处理签名数据
								this.signImages = {}; // 初始化signImages
								signResult.data.forEach(sign => {
									if (sign.position && this.sealOptionsKey.includes(sign.position)) {
										if (!this.signImages[sign.position]) {
											this.signImages[sign.position] = []; // 初始化数组
										}
										this.signImages[sign.position].push({
											imageUrl: sign.signImg,
											signUNID: sign.signUNID,
											hetype: sign.type
										});
									}
								});
								console.log(this.signImages); // 检查signImages数据
							}
						}
						// 设置页面标题
						uni.setNavigationBarTitle({
							title: this.pageTitle
						});
					}
				} catch (error) {
					console.log(error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}
			},
			loadFile(file) {
				const timestamp = new Date().getTime();
				const encodedUrl = encodeURIComponent(config.importantBaseUrl+ file.fileUrl);
				console.log(encodedUrl)
				const url = `https://xdoc.sdhwj.com/view?mtime=${timestamp}&src=${encodedUrl}`;
				//打开新网页
				window.open(url, '_blank');
			},
			toggleMenu() {
				this.isExpanded = !this.isExpanded;
			},
			async handleMenuClick(action) {
				switch (action) {
					case '批注':
						this.handleTextSign();
						break;
					case '退回':
						this.getBackNodes();
						break;
					case '发送':
						this.getNextTasks();
						break;
					case '签收':
						try {
							uni.showLoading({
								title: '签收中...'
							});
							const params = {
								id: this.formData.bpm.taskId,// 从formData.bpm中获取taskId
								'__sid': uni.getStorageSync('sessionid'), // 从登录接口返回的sessionId
							};
							const headers = {
								'__sid': uni.getStorageSync('sessionid'), // 从登录接口返回的sessionId
								'x-remember': uni.getStorageSync('x-remember') // 从登录接口返回的x-remember
							};
							const response = await this.$u.api.getQianshou(params, headers);
							if (response && response.code === 1) {
								uni.showToast({
									title: '签收成功',
									icon: 'success'
								});
								// 签收成功后返回列表
							} else {
								throw new Error(response?.msg || '签收失败');
							}
						} catch (error) {
							console.error('签收失败:', error);
							uni.showToast({
								title: error.message || '签收失败',
								icon: 'none'
							});
						} finally {
							uni.hideLoading();
						}
						break;
				}
			},
			openSealDialog() {
				this.isExpanded = false;
				this.showSealDialog = true;
			},
			async loginSignServer() {
				try {
					const userName = uni.getStorageSync('userName');
					if (!userName) {
						uni.showToast({
							title: '请先登录系统',
							icon: 'none'
						});
						return;
					}
					// 调用登录接口
					const result = await signature.login(userName);
					if (result && result.status.errCode === "0") {
						this.isSignServerLoggedIn = true;
						// uni.showToast({
						// 	title: '签章服务器登录成功',
						// 	icon: 'success'
						// });
					} else {
						throw new Error(result?.message || '登录失败');
					}
				} catch (error) {
					console.error('签章服务器登录失败:', error);
					uni.showToast({
						title: '签章服务器登录失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			async addSeal() {
				if (!this.isSignServerLoggedIn) {
					uni.showToast({
						title: '请先登录签章服务器',
						icon: 'none'
					});
					await this.loginSignServer();
					return;
				}

				try {
					const userName = uni.getStorageSync('userName');
					if (!userName) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return;
					}

					// 获取图章列表
					const result = await signature.listStamps(userName);
					if (result && result.status.errCode === "0") {
						this.sealList = result.data.map(stamp => ({
							...stamp,
							imageUrl: stamp.signImg,
							name: stamp.signName,
							signUser: stamp.signUser
						}));
						this.showSealList = true;
					} else {
						uni.showToast({
							title: '获取图章列表失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取图章列表失败:', error);
					uni.showToast({
						title: '获取图章列表失败',
						icon: 'none'
					});
				}
			},
			// 选择图章
			async selectSeal(seal) {
				try {
					const userName = uni.getStorageSync('userName');
					if (!userName) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return;
					}

					// 创建表单字段
					const formFields = {
						formId: uni.getStorageSync('bizKey') || 'testFormId',
						position: this.sealOptionsKey[this.sealIndex],
						value: [{
								name: 'name',
								value: userName,
								primaryName: '姓名'
						}]
					};

					// 添加图章签名
					const result = await signature.addStampSign(
						userName,
						seal.signSN,
						formFields,
						this.withDate
					);

						// uni.showToast({
						// 	title: '添加图章成功',
						// 	icon: 'success'
						// });
						this.showSealList = false;
					this.showSealDialog = false;
					// 刷新签章列表
					this.loadFormData();
				} catch (error) {
					console.error('添加图章失败:', error);
					uni.showToast({
						title: error,
						icon: 'none'
					});
				}
			},
			onSealPositionChange(e) {
				this.sealIndex = e.detail.value;
			},
			onDateChange(e) {
				this.withDate = e.detail.value;
			},
			onCommentPositionChange(e) {
				this.commentPositionIndex = e.detail.value;
			},
			addComment() {
				try {
					const userName = uni.getStorageSync('userName');
					if (!userName) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return;
					}

					if (!this.commentContent.trim()) {
						uni.showToast({
							title: '请输入批注内容',
							icon: 'none'
						});
						return;
					}

					const position = this.sealOptionsKey[this.commentPositionIndex];
					
					// 创建canvas上下文
					const ctx = uni.createCanvasContext('signatureCanvas', this);
					
					// 设置画布大小
					const canvasWidth = 300;
					const canvasHeight = 100;
					
					// 清空画布
					ctx.clearRect(0, 0, canvasWidth, canvasHeight);
					
					// 设置背景为透明
					ctx.setFillStyle('rgba(0, 0, 0, 0)');
					ctx.fillRect(0, 0, canvasWidth, canvasHeight);
					
					// 设置文字样式
					ctx.setFontSize(this.textSignFontSize || 60);
					ctx.setTextAlign('center');
					ctx.setTextBaseline('middle');
					ctx.setFillStyle(this.textSignColor || '#000000');
					
					// 设置文字加粗
					ctx.font = `bold ${this.textSignFontSize || 60}px ${this.textSignFontFamily || '宋体'}`;
					
					// 计算文字位置（完全居中）
					const x = canvasWidth / 2;
					const y = canvasHeight / 2;
					
					// 绘制文字
					ctx.fillText(this.commentContent, x, y);
					
					// 将canvas内容转换为图片
					ctx.draw(true, () => {
						// 延迟获取canvas，确保渲染完成
						setTimeout(() => {
							uni.canvasToTempFilePath({
								canvasId: 'signatureCanvas',
								width: canvasWidth,
								height: canvasHeight,
								destWidth: canvasWidth,
								destHeight: canvasHeight,
								success: async (res) => {
									console.log('canvas转图片成功:', res);
									try {
										const result = await signature.addTextSignature(
											this.commentContent,
											userName,
											res.tempFilePath,
											uni.getStorageSync('bizKey'),
											position
										);
										
										if (result && result.status.errCode === "0") {
											uni.showToast({
												title: '添加批注成功',
												icon: 'success'
											});
											this.showCommentDialog = false;
											// 刷新表单数据以显示新添加的批注
											this.loadFormData();
										} else {
											throw new Error(result?.message || '添加批注失败');
										}
									} catch (error) {
										console.error('添加批注失败:', error);
										uni.showToast({
											title: error.message || '添加批注失败',
											icon: 'none'
										});
									}
								},
								fail: (error) => {
									console.error('canvas转图片失败:', error);
									uni.showToast({
										title: '生成签名失败',
										icon: 'none'
									});
								}
							}, this);
						}, 500);
					});
				} catch (error) {
					console.error('添加批注失败:', error);
					uni.showToast({
						title: '添加失败',
						icon: 'none'
					});
				}
			},
			handleTextSign() {
				this.showCommentDialog = true;
			},
			onColorChange(e) {
				const colors = ['#000000', '#FF0000', '#FFFF00', '#FFFFFF', '#00FF00', '#0000FF', '#800080'];
				this.textSignColor = colors[e.detail.value];
			},
			// 处理长按事件
			handleLongPress(signUNID, type) {
				if (!signUNID) {
					uni.showToast({
						title: '无法获取签章信息',
						icon: 'none'
					});
					return;
				}
				
				uni.showModal({
					title: '提示',
					content: `是否删除${type === 'seal' ? '签章' : '批注'}？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								const result = await signature.deleteSignature(
									uni.getStorageSync('bizKey'),
									signUNID
								);
								
								if (result && result.errCode === "0") {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
									// 刷新签章列表
									this.loadFormData();
								} else {
									throw new Error(result?.message || '删除失败');
								}
							} catch (error) {
								console.error('删除失败:', error);
								uni.showToast({
									title: error.message || '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			async getBackNodes() {
				try {
					uni.showLoading({
						title: '加载中...'
					});
					const response = await this.$u.api.getBackNodes({
						__sid: uni.getStorageSync('sessionid'),
						id: uni.getStorageSync('taskId'),
					});
					if (response && response.code === 1 && response.data) {
						const backActivities = response.data.backActivity || [];
						if (backActivities.length === 0) {
							uni.showToast({
								title: '当前节点无可退回节点',
								icon: 'none'
							});
							return;
						}
						
						this.backNodes = backActivities.map(node => ({
							activityId: node.activityId,
							activityName: node.activityName,
							nextUserCodes: node.assignee
						}));
						console.log('backNodes:', this.backNodes);
						this.showBackDialog = true;
					} else {
						uni.showToast({
							title: response?.msg || '获取退回列表失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取退回列表失败:', error);
					uni.showToast({
						title: '获取退回列表失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			onBackNodeChange(e) {
				this.backNodeIndex = e.detail.value;
			},
			async confirmBack() {
				uni.showLoading({
					title: '正在提交...'
				});
				if (this.backNodes.length === 0 || this.backNodeIndex === null) {
					uni.hideLoading();
					uni.showToast({
						title: '请选择退回节点',
						icon: 'none'
					});
					return;
				}

				const selectedNode = this.backNodes[this.backNodeIndex];
				try {
					await this.backTask(selectedNode.activityId, selectedNode.nextUserCodes, this.backCommentContent);
					this.showBackDialog = false;
				} finally {
					uni.hideLoading();
				}
			},
			async backTask(activityId, nextUserCodes, comment) {
				try {
					const response = await this.$u.api.backTask({
						__sid: uni.getStorageSync('sessionid'),
						id: uni.getStorageSync('taskId'),
						activityId,
						nextUserCodes,
						Comment: comment
					});
					if (response && response.code === 1) {
						uni.showToast({
							title: '退回成功',
							icon: 'success',
							duration: 2000,
							success: () => {
								// 延迟跳转，让用户看到成功提示
								setTimeout(() => {
									uni.redirectTo({
										url: '/pages/sys/msg/list-item'
									});
								}, 2000);
							}
						});
					} else {
						throw new Error(response?.message || '退回失败');
					}
				} catch (error) {
					console.log(error);
					uni.showToast({
						title: error.message || '退回失败',
						icon: 'none'
					});
				}
			},
			mounted() {
				window.__vue__ = this;
				// 重置颜色选择器
				this.textSignColor = '#000000';
				// 添加全局点击事件监听
				document.addEventListener('click', this.handleClickOutside);
			},
			beforeDestroy() {
				// 移除全局点击事件监听
				document.removeEventListener('click', this.handleClickOutside);
			},
			previewSignature() {
				if (!this.commentContent.trim()) {
					uni.showToast({
						title: '请输入批注内容',
						icon: 'none'
					});
					return;
				}

				const ctx = uni.createCanvasContext('signatureCanvas', this);
				const canvasWidth = 300;
				const canvasHeight = 100;

				ctx.clearRect(0, 0, canvasWidth, canvasHeight);
				ctx.setFillStyle('rgba(0, 0, 0, 0)');
				ctx.fillRect(0, 0, canvasWidth, canvasHeight);

				ctx.setFontSize(this.textSignFontSize || 60);
				ctx.setTextAlign('center');
				ctx.setTextBaseline('middle');
				ctx.setFillStyle(this.textSignColor || '#000000');
				ctx.font = `bold ${this.textSignFontSize || 60}px ${this.textSignFontFamily || '宋体'}`;

				const x = canvasWidth / 2;
				const y = canvasHeight / 2;

				ctx.fillText(this.commentContent, x, y);

				ctx.draw(true, () => {
					setTimeout(() => {
						uni.canvasToTempFilePath({
							canvasId: 'signatureCanvas',
							width: canvasWidth,
							height: canvasHeight,
							destWidth: canvasWidth,
								destHeight: canvasHeight,
								success: (res) => {
									this.previewImage = res.tempFilePath;
									this.$refs.previewPopup.open('center');
								},
								fail: (error) => {
									console.error('生成预览图片失败:', error);
									uni.showToast({
										title: '生成预览失败',
										icon: 'none'
									});
							}
						}, this);
					}, 500);
				});
			},
			closePreview() {
				this.$refs.previewPopup.close();
			},
			async getNextTasks() {
				try {
					uni.showLoading({
						title: '加载中...'
					});
					const response = await this.$u.api.getNextTasks({
						__sid: uni.getStorageSync('sessionid'),
						procInsId: this.formData.bpm.procInsId,
						formKey: this.formData.formKey,
						activityId: this.formData.bpm.activityId,
						taskId: this.formData.bpm.taskId,
						bizKey: uni.getStorageSync('bizKey')
					});

					if (response && response.code === 1 && response.data) {
						
						this.nextTasks = response.data;
						// 检查是否需要显示参与人员选择
						const selectedTask = this.nextTasks[this.nextTaskIndex];
						this.showParticipants = selectedTask && selectedTask.label !== '结束';
						if (this.showParticipants) {
							await this.getNextUsers(selectedTask);
						}
						this.showSendDialog = true;
					} else {
						uni.showToast({
							title: response?.msg || '获取下一环节失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取下一环节失败:', error);
					uni.showToast({
						title: '获取下一环节失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			async getNextUsers(task) {
				try {
					const response = await this.$u.api.getNextUsers({
						__sid: uni.getStorageSync('sessionid'),
						userCodes: task.usersList,
						roleCodes: task.rolesList
					});

					if (response && response.code === 1 && response.data) {
						this.participants = response.data.list;
					} else {
						uni.showToast({
							title: response?.msg || '获取参与人员失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取参与人员失败:', error);
					uni.showToast({
						title: '获取参与人员失败',
						icon: 'none'
					});
				}
			},
			onNextTaskChange(e) {
				this.nextTaskIndex = e.detail.value;
				const selectedTask = this.nextTasks[this.nextTaskIndex];
				this.showParticipants = selectedTask && selectedTask.label !== '结束';
				if (this.showParticipants) {
					this.getNextUsers(selectedTask);
				} else {
					this.participants = [];
				}
				this.selectedParticipants = ''; // 清空已选参与人员
				this.selectedParticipantIndex = 0; // 重置索引
			},
			onParticipantChange(e) {
				this.selectedParticipantIndex = e.detail.value;
				this.selectedParticipants = this.participants[this.selectedParticipantIndex].userCode;
			},
			async confirmSend() {
				const selectedTask = this.nextTasks[this.nextTaskIndex];
				if (!selectedTask) {
					uni.showToast({
						title: '请选择下一环节',
						icon: 'none'
					});
					return;
				}

				if (selectedTask.label === '结束') {
					uni.showToast({
						title: '此环节请在电脑端处理',
						icon: 'none'
					});
					return;
				}

				// 使用单选的参与人员进行验证和发送
				if (this.showParticipants && !this.selectedParticipants) {
					uni.showToast({
						title: '请选择参与人员',
						icon: 'none'
					});
					return;
				}

				try {
					uni.showLoading({
						title: '发送中...'
					});

					// 处理下一环节名称
					let huiqian = '';
					if (selectedTask.value) {
						
						if (selectedTask.value.includes('==')) {
							const splitArr = selectedTask.value.split('==');
							if (splitArr.length === 2) {
								huiqian = splitArr[1].replace("'", "").replace("'}", "");
							} else {
								throw new Error('获取的下一环节数据中value字段格式不正确');
							}
						} else {
							throw new Error('获取的下一环节数据中value字段没有==导致异常');
						}
					}

					// 构建基础参数
					const baseParams = {
						__sid: uni.getStorageSync('sessionid'),
						formKey: this.formData.formKey,
						id: this.formData.id,
						title: this.formData.title,
						huiqian: huiqian,
						'bpm.taskId': this.formData.bpm.taskId,
						'bpm.procInsId': this.formData.bpm.procInsId,
						'bpm.activityId': this.formData.bpm.activityId,
						'bpm.priority': String(this.formData.bpm.priority)
					};

					// 如果有选中的参与人员，添加到参数中
					if (this.selectedParticipants) {
						baseParams['bpm.nextUserCodes'] = this.selectedParticipants;
					}

					// 根据isFw和gwTypeValue选择不同的发送接口和构建不同的参数
					let response;
					const isFw = this.formData.isFw === "true";
					const gwTypeValue = this.gwTypeValue;
					if (isFw) {
						// 发文相关表单
						const fwParams = {
							...baseParams,
							__sid: uni.getStorageSync('sessionid'), // 确保 session ID 在参数中
							nianhao: this.formData.nianhao || '', // 年号
							fawenhao: this.formData.fawenhao || '', // 发文号
							fujian: this.formData.fujian || '', // 附件
							fenfa: this.formData.fenfa || '', // 分发
							chaosong: this.formData.chaosong || '', // 主呈
							zhuban: this.formData.zhuban || '', // 主办单位
							nigaoren: this.formData.nigaoren || '', // 拟稿人
							dianhua: this.formData.dianhua || '', // 电话
							zwfs: this.formData.zwfs || '', // 正文方式
							fjfs: this.formData.fjfs || '', // 附件方式
							dazi: this.formData.dazi || '', // 打字
							jiaodui: this.formData.jiaodui || '', // 校对
							yinshua: this.formData.yinshua || '', // 印刷
							yongyin: this.formData.yongyin || '', // 用印
							fengfa: this.formData.fengfa || '', // 分发
							bgssh: this.formData.bgssh || '', // 办公室审核
							wenjianzi: this.formData.wenjianzi || '', // 文件号
							qianfa: this.formData.qianfa || '' // 签发
						};
						
						if (gwTypeValue && gwTypeValue.includes("czdb")) {
							// 传真电报
							response = await this.$u.api.sendFw(fwParams);
						} else {
							// 发文
							response = await this.$u.api.sendFw(fwParams);
						}
					} else {
						// 收文相关表单 (包括呈报件)
						const swParams = {
							...baseParams,
							__sid: uni.getStorageSync('sessionid'), // 确保 session ID 在参数中
							nianhao: this.formData.nianhao || '', // 年号
							fawenhao: this.formData.fawenhao || '', // 发文号
							fujian: this.formData.fujian || '', // 附件 / 是否急件 (收文)
							zwfs: this.formData.zwfs || '', // 正文方式 / 份数 (收文)
							fenfa: this.formData.fenfa || '', // 分发
							chaosong: this.formData.chaosong || '', // 主呈
							zhuban: this.formData.zhuban || '', // 主办单位
							nigaoren: this.formData.nigaoren || '', // 拟稿人
							dianhua: this.formData.dianhua || '', // 电话
							bgssh: this.formData.bgssh || '', // 办公室意见
							fabufanwei: this.formData.fabufanwei || '', // 来文字号 (收文用), 呈报件可能用作其他
							qianfa: this.formData.qianfa || '', // 领导批示
							remarks: this.formData.remarks || '', // 办理结果
							// Added for 请示件/收文
							zhusong: this.formData.zhusong || '', // 来文单位
							createtime: this.formData.createtime || '', // 来文时间
							// 呈报件特有参数
							jubenNianhao: this.formData.jubenNianhao || '',
							jubenBianhao: this.formData.jubenBianhao || '',
							bumenNianhao: this.formData.bumenNianhao || '',
							bumenBianhao: this.formData.bumenBianhao || '',
							zhucheng: this.formData.zhucheng || '',
							shenYueOpinion: this.formData.shenYueOpinion || '',
							departmentAuditOpinion: this.formData.departmentAuditOpinion || '',
							chengbaoUnit: this.formData.chengbaoUnit || '',
							// 外出请示单特有参数
							userName: this.formData.userName || '', // 姓名
							zhiwu: this.formData.zhiwu || '', // 职务
							shiyou: this.formData.shiyou || '', // 事由
							mudidi: this.formData.mudidi || '', // 目的地
							sdt: this.formData.sdt || '', // 开始时间
							zcgzfztz: this.formData.zcgzfztz || '', // 主持工作负责同志
							bgsyj: this.formData.bgsyj || '', // 办公室意见
							fenguanlingdao: this.formData.fenguanlingdao || '', // 分管领导审批
							zhuyaofuzeren: this.formData.zhuyaofuzeren || '', // 主要负责人审批
							tianbaolianxiren: this.formData.tianbaolianxiren || '', // 填报联系人
							tianbaorenlianxifangshi: this.formData.tianbaorenlianxifangshi || '' // 联系电话
						};

						switch (gwTypeValue) {
							case "wcbg":
								// 外出报告单
								response = await this.$u.api.sendWcbg(swParams);
								break;
							case "lbbg":
								// 来宾报告
								const lbbgParams = {
									...baseParams,
									// 精确匹配Java后端期望的字段
									bgDt: this.formData.bgDt || '',
									lbdw: this.formData.lbdw || '',
									lbrs: this.formData.lbrs || '',
									zbxm: this.formData.zbxm || '',
									zbzw: this.formData.zbzw || '',
									ptry: this.formData.ptry || '',
									xcap: this.formData.xcap || '', // 对应Java的xcap
									bgsyj: this.formData.bgsyj || '',
									ldps: this.formData.ldps || '',
									remarks: this.formData.remarks || '',
								};
								console.log('Sending lbbgParams:', lbbgParams);
								response = await this.$u.api.sendLbbg(lbbgParams);
								break;
							case "cbj":
								// 呈报件
								response = await this.$u.api.sendSw(swParams);
								break;
							case "qsj":
								// 收文请示件
								response = await this.$u.api.sendSw(swParams);
								break;
							default:
								// 收文
								response = await this.$u.api.sendSw(swParams);
								break;
						}
					}

					if (response && response.code === 1) {
						uni.showToast({
							title: '发送成功',
							icon: 'success'
						});
						this.showSendDialog = false;
						this.selectedParticipants = ''; // 发送成功后清空已选人员
						// 可以在这里添加发送成功后的处理逻辑，比如返回列表页
						uni.redirectTo({
                    		url: '/pages/sys/msg/list-item'
                		});
					} else {
						throw new Error(response?.msg || '发送失败');
					}
				} catch (error) {
					console.error('发送失败:', error);
					uni.showToast({
						title: error.message || '发送失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			closeSendDialog() {
				this.showSendDialog = false;
			},
			showAllParticipants() {
				this.filteredParticipants = this.participants;
				this.showSearchResults = true;
			},
			handleSearch() {
				const keyword = this.searchKeyword.toLowerCase().trim();
				if (!keyword) {
					this.filteredParticipants = [...this.participants];
				} else {
					this.filteredParticipants = this.participants.filter(user => {
						return user.userName.toLowerCase().includes(keyword);
					});
				}
				this.showSearchResults = true;
			},
			selectParticipant(user) {
				this.selectedParticipants = user.userCode;
				this.searchKeyword = `${user.userName} (${user.employee.office.officeName})`;
				this.showSearchResults = false;
			},
			handleClickOutside(event) {
				// 如果点击的不是搜索容器内的元素，则收起下拉列表
				const searchContainer = document.querySelector('.search-container');
				if (searchContainer && !searchContainer.contains(event.target)) {
					this.showSearchResults = false;
				}
			},
		},
		computed: {
			pageTitle() {
				const gwTypeValue = this.gwTypeValue;
				switch (gwTypeValue) {
					case 'cbj':
						return '呈报件';
					case 'czdb':
						return '传真电报';
					case 'sw':
						return '收文流程';
					case 'lbbg':
						return '来宾报告';
					case 'qsj':
						return '请示件';
					case 'wcbg':
						return '外出报告单';
					default:
						return '发文流程'; // Default title
				}
			}
		},
		watch: {
			showBackDialog(newVal) {
				if (newVal) {
					// 打开弹窗时清空退回意见并重置选中节点
					this.backCommentContent = '';
					this.backNodeIndex = 0;
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
.form-view {
  padding: 20px;
}

.form-item {
  margin-bottom: 15px;
}

.form-item-title {
  font-weight: bold;
  margin-bottom: 5px;
}


.btn-group {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.send-btn,
.return-btn {
  margin: 0 10px;
}

/* 操作按钮相关样式 */
.float-action-btn {
  position: fixed;
  right: 15rpx;
  top: 10rpx;
  width: 70rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.float-action-btn .icon {
  color: white;
  font-size: 20rpx;
}

.action-menu {
  position: fixed;
  right: 3rpx;
  top: 80rpx;
  width: 100rpx;
  z-index: 9999;
}

.menu-item {
  background: white;
  padding: 15rpx;
  margin-bottom: 10rpx;
  border-radius: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  text-align: center;
  font-size: 24rpx;
  color: #333;
  transform-origin: bottom right;
}

.menu-item:active {
  background: #f0f0f0;
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  opacity: 0;
  transform: scale(0);
}

.menu-item-sign {
  background: linear-gradient(135deg, #FF6347, #FF4500) !important;
  color: white !important;
  box-shadow: 0 4rpx 12rpx rgba(34, 139, 34, 0.3) !important;
}

.menu-item-comment {
  background: linear-gradient(135deg, #6495ED, #1E90FF) !important;
  color: white !important;
  box-shadow: 0 4rpx 12rpx rgba(30, 144, 255, 0.3) !important;
}

.menu-item-reject {
  background: linear-gradient(135deg, #FFA500, #FF8C00) !important;
  color: white !important;
  box-shadow: 0 4rpx 12rpx rgba(255, 69, 0, 0.3) !important;
}

.menu-item-send {
  background: linear-gradient(45deg, #ff8c00, #ff4500) !important;
  color: #fff !important;
  box-shadow: 0 2px 4px rgba(255, 140, 0, 0.3) !important;
}

.menu-item-sign-off {
  background-color: #0fb12d9a; // 蓝色 for 签收
  color: #fff !important;
}

/* 弹窗相关样式 */
.seal-dialog-bg {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.seal-dialog {
  background: #fff;
  border-radius: 10rpx;
  padding: 40rpx;
  width: 80vw;
  z-index: 999;
}

.dialog-content {
  padding: 30rpx;
}

.dialog-footer {
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  border-top: 1rpx solid #eee;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 12rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background: #fff;
  box-sizing: border-box;
}

.form-picker {
  width: 100%;
}

.picker-content {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
}

.picker-arrow {
  color: #999;
  font-size: 24rpx;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
  border: 1rpx solid #ddd;
  margin: 0;
  padding: 0 30rpx;
  height: 56rpx;
  line-height: 56rpx;
  font-size: 24rpx;
  border-radius: 6rpx;
}

.btn-confirm {
  background: #007AFF;
  color: #fff;
  border: none;
  margin: 0;
  padding: 0 30rpx;
  height: 56rpx;
  line-height: 56rpx;
  font-size: 24rpx;
  border-radius: 6rpx;
}

/* 搜索相关样式 */
.search-container {
  position: relative;
  width: 100%;
}

.search-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background: #fff;
  box-sizing: border-box;
}

.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  max-height: 400rpx;
  background: #fff;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  margin-top: 4rpx;
  z-index: 99999;
}

.search-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
  font-size: 28rpx;
}

.search-item:active {
  background: #f8f8f8;
}

.search-item:last-child {
  border-bottom: none;
}
/* 图章列表弹窗样式 */
	.seal-list-dialog-bg {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
	}

	.seal-list-dialog {
		background-color: #fff;
		border-radius: 10rpx;
		width: 90%;
		max-width: 800rpx;
		padding: 30rpx;
	}

	.seal-list-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
		text-align: center;
		color: #333;
	}

	.seal-list-content {
		max-height: 800rpx;
		overflow-y: auto;
	}

	.seal-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.seal-item:hover {
		background-color: #f5f5f5;
	}

	.seal-image {
		width: 90rpx;
		height: 80rpx;
		margin-right: 10rpx !important;
		object-fit: contain;
		// background-color: #f8f8f8;
		// border: 1px solid #eee;
		border-radius: 4rpx;
		padding: 0rpx;
	}

	.seal-name {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}

	.seal-list-footer {
		margin-top: 30rpx;
		text-align: right;
		padding-top: 20rpx;
		border-top: 1rpx solid #eee;
	}

</style>